package com.highspeed.bdk.gateway.socket.analyze.message.gui.command;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;

/**
 * 序号自动增长器，返回short类型，如果超过最大值，则重新为零
 */
public class SeqGenerator {
    private static final Log LOG = LogFactory.getLog(SeqGenerator.class);

    public static final synchronized short autoIncrementSeq() {
        File file = new File("seq.dat");
        DataInputStream dis = null;
        DataOutputStream dos = null;
        Short seq = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
                seq = 0;
                dos = new DataOutputStream(new FileOutputStream(file));
                dos.writeShort(seq + 1);
                return seq;
            }
            dis = new DataInputStream(new FileInputStream(file));
            seq = dis.readShort();
            dos = new DataOutputStream(new FileOutputStream(file));

            //超出short类型，重置为零
            short newSeq = (short) (seq + 1);
            if (newSeq < 0) {
                newSeq = 0;
            }
            dos.writeShort(newSeq);
        } catch (FileNotFoundException e) {
            LOG.error(e);
            e.printStackTrace();
        } catch (IOException e) {
            LOG.error(e);
            e.printStackTrace();
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    LOG.error(e);
                }
            }
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    LOG.error(e);
                }
            }
        }
        return seq;
    }
}
